package com.tyl.controller;

import com.tyl.pojo.Books;
import com.tyl.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

@Controller
@RequestMapping("/book")
public class BookController {
    @Autowired
    @Qualifier("BookServiceImpl")
    private BookService bookService;

    //查询全部书籍并且返回界面
    @RequestMapping("/allBooks")
    public String list(Model model){
        List<Books> list=bookService.queryAllBook();
        model.addAttribute("list",list);
        return "allBooks";
    }

    //查询全部书籍并且返回界面
    @RequestMapping("/queryAllBooks")
    public String allBooks(Model model){
        List<Books> list=bookService.queryAllBook();
        model.addAttribute("list",list);
        return "allBooks";
    }

    //添加书籍
    @RequestMapping("/toAddBook")
    public  String toAddPaper(){
        return "addBook";
    }
    @RequestMapping("/addBook")
    public String addBooks(Books books){
        bookService.addBook(books);
        return "redirect:/book/allBooks";//重定向
    }

    @RequestMapping("/toUpdateBook")
    public String toUpdateBook(Model model, int id) {
         Books books = bookService.queryBookById(id);
        System.out.println(books);
        model.addAttribute("book",books);
        return "updateBook";
    }

    @RequestMapping("/updateBook")
    public  String updateBook(Model model,Books book){
        bookService.updateBookById(book);
        Books books = bookService.queryBookById(book.getBookID());
        model.addAttribute("books",books);
        return "redirect:/book/allBooks";//重定向
    }

    @RequestMapping("/del")
    public String deleteBook(int id) {
        bookService.deleteBookById(id);
        return "redirect:/book/allBooks";
    }


    @RequestMapping("/queryBookByName")
    public String queryBookName(String bookName ,Model model){
        List<Books> list = new ArrayList<>();
        System.out.println(bookName);
        if (bookName==null||bookName.equals("")){
            list = bookService.queryAllBook();
        }
        Books books = bookService.queryBookName(bookName);
        System.err.println(books);
        list.add(books);
        model.addAttribute("list",list);
        bookService.queryBookName(bookName);
        return "allBooks";
    }
}